package cn.wolfcode.job;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**

 * 用于处理用户缓存的定时任务
 * 为了保证Redis中的内存的有效使用。
 * 我们默认保留7天内的用户缓存数据，每天凌晨的时候会把7天前的用户登录缓存数据删除掉
 */
@Component
@Setter
@Getter
@RefreshScope
@Slf4j
public class SeckillProductInitJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Value("${sharding.count.initSeckillProduct}")
    private Integer shardingTotalCount;
    @Value("${sharding.parameters.initSeckillProduct}")
    private String shardingItemParameters;

    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext.getShardingParameter());
    }
    private void doWork(String shardingParameter) {
        log.info("----------------开始定时任务----------------");
        Result<List<SeckillProductVo>> listResult = seckillProductFeignApi.selectByTime(Integer.parseInt(shardingParameter));
        if (listResult.hasError()){
            log.error("【定时任务】：查询秒杀商品vo异常,Result=》{}", JSON.toJSONString(listResult));
            throw new BusinessException(CommonCodeMsg.ILLEGAL_OPERATION);
        }
        if (listResult.getData().size() == 0){
            log.info("【定时任务】：当天参加的秒杀商品为空");
            return;
        }
        String key = JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(shardingParameter);
        listResult.getData().forEach(seckillProductVo -> {
            log.info("key="+ key + "  hash_key=" +seckillProductVo.getId());
            redisTemplate.opsForHash().put(key,String.valueOf(seckillProductVo.getId()),JSON.toJSONString(seckillProductVo));
        });
        log.info("----------------定时任务结束----------------");
    }


}
